// Copyright (c) 2023 坚果派
// 公众号：nutpi
// 电话：17752170152
// 官网：https://www.nutpi.net/
// All rights reserved.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/health_news_provider.dart';
import '../providers/health_reminder_provider.dart';
import '../providers/page_navigation_provider.dart';
import '../services/url_service.dart';

class DashboardPage extends StatelessWidget {
  const DashboardPage({super.key});

  @override
  Widget build(BuildContext context) {
    final newsProvider = Provider.of<HealthNewsProvider>(context);
    final reminderProvider = Provider.of<HealthReminderProvider>(context);

    // 确保在页面加载时初始化数据
    if (newsProvider.newsList.isEmpty && !newsProvider.isLoading) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        newsProvider.loadInitialNews();
      });
    }

    if (reminderProvider.tipContent.isEmpty && !reminderProvider.isLoading) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        reminderProvider.fetchHealthReminder();
      });
    }

    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildWelcomeCard(context),
            const SizedBox(height: 20),
            _buildHealthReminderCard(context, reminderProvider),
            const SizedBox(height: 20),
            _buildLatestNewsSection(context, newsProvider),
            const SizedBox(height: 20),
            _buildQuickAccessGrid(context),
          ],
        ),
      ),
    );
  }

  Widget _buildWelcomeCard(BuildContext context) {
    return Card(
      elevation: 4,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                CircleAvatar(
                  backgroundColor: Theme.of(context).colorScheme.primary,
                  radius: 24,
                  child:
                      const Icon(Icons.person, color: Colors.white, size: 32),
                ),
                const SizedBox(width: 16),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '欢迎使用健康助手',
                      style: Theme.of(context).textTheme.titleLarge,
                    ),
                    Text(
                      '今天是 ${DateTime.now().year}年${DateTime.now().month}月${DateTime.now().day}日',
                      style: Theme.of(context).textTheme.bodySmall,
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHealthReminderCard(
      BuildContext context, HealthReminderProvider provider) {
    return Card(
      elevation: 3,
      color: Theme.of(context).colorScheme.primaryContainer,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  Icons.tips_and_updates,
                  color: Theme.of(context).colorScheme.onPrimaryContainer,
                ),
                const SizedBox(width: 8),
                Text(
                  '今日健康提示',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Theme.of(context).colorScheme.onPrimaryContainer,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            provider.isLoading
                ? const Center(child: CircularProgressIndicator())
                : Text(
                    provider.tipContent,
                    style: TextStyle(
                      fontSize: 16,
                      color: Theme.of(context).colorScheme.onPrimaryContainer,
                    ),
                  ),
            const SizedBox(height: 8),
            Align(
              alignment: Alignment.centerRight,
              child: TextButton.icon(
                icon: const Icon(Icons.refresh),
                label: const Text('换一条'),
                onPressed: () => provider.fetchHealthReminder(),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLatestNewsSection(
      BuildContext context, HealthNewsProvider provider) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              '最新健康资讯',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
            ),
            TextButton(
              onPressed: () {
                // 导航到健康资讯页面 (index 0)
                Provider.of<PageNavigationProvider>(context, listen: false)
                    .changePage(0);
              },
              child: const Text('查看全部'),
            ),
          ],
        ),
        if (provider.isLoading && provider.newsList.isEmpty)
          const Center(child: CircularProgressIndicator())
        else if (provider.newsList.isEmpty)
          const Center(child: Text('暂无最新资讯'))
        else
          SizedBox(
            height: 220,
            child: ListView.builder(
              itemCount: provider.newsList.length,
              itemBuilder: (context, index) {
                final news = provider.newsList[index];
                return ListTile(
                  title: Text(news.title),
                  subtitle: Text(news.description),
                  onTap: () async {
                    if (news.url.isNotEmpty) {
                      await UrlService.openUrl(news.url);
                    }
                  },
                );
              },
            ),
          ),
      ],
    );
  }

  Widget _buildQuickAccessGrid(BuildContext context) {
    // Implementation of _buildQuickAccessGrid method
    throw UnimplementedError();
  }
}
